package com.trade.system.filter;

import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * Class Description: 跨域资源请求过滤器
 *  Cross-Origin Resource Sharing(跨域资源共享，简写为CORS)
 *
 * @Version v1.0 2017/9/16 22:12
 * @JDK version 1.8.0_51
 * @Author zfb
 */
public class CORSFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        response.setHeader("Access-Control-Allow-Origin",request.getHeader("Origin"));  //允许访问的URL,从request对象中获取，相当于允许所有请求
        response.setHeader("Access-Control-Allow-Credentials", "true"); //允许发送Cookie
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); //允许请求的方式
        response.setHeader("Access-Control-Max-Age", "3600"); //表明在3600秒内，不需要再发送预检验请求，可以缓存该结果
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with"); //表明它允许跨域请求包含content-type头
        filterChain.doFilter(request,response);
    }
}
